<template>
  <el-container class="container">
    <el-aside class="aside">
      <contact-list :contact-list="contactList" @select="handleContactSelect"></contact-list>
    </el-aside>
    <el-main class="main">
      <chat-box v-if="selectedContact !== null" :message-list="messageList" :contact="selectedContact" :selected-position="getSelectedPosition()" @send="sendMessageToSocket" ></chat-box>
    </el-main>
  </el-container>

</template>

<script>
import {useAccountStore} from "@/stores/account";
import { ElMessage } from 'element-plus'
import ChatBox from "@/views/ChatView/ChatBox.vue";
import ContactList from "@/views/ChatView/ContactList.vue";
import {getContactList, getContactListWithSelectedId, getMessages, getPositionList} from "@/api/path/chat";
import {useSocketStore} from "@/stores/socket.ts";
export default {
  name: "ChatView",
  components: {
    ContactList,
    ChatBox,
  },
  data() {
    return {
      accountStore: useAccountStore(),
      socketStore: useSocketStore(),
      contactList: [],
      messageList: [],
      positionList: [],
      selectedContact: null,
    };
  },
  async mounted() {
    await this.reqGetContactList();
    await this.reqGetPositionList();
    console.log('[positionList]', this.positionList);
    this.receiveMessageFromSocket();
    if (this.$route.query.id !== undefined) {
      await this.handleContactSelect(this.$route.query.id);
    }
  },
  methods: {

    async reqGetContactList() {
      const response = this.$route.query.id === undefined ? await getContactList() : await getContactListWithSelectedId(this.$route.query.id);
      if (response.errno === 1) {
        this.contactList = response.result_list;
      }
      else {
        ElMessage.error(response.msg);
      }
    },

    async reqGetMessageList(userId) {
      const response = await getMessages(userId);
      if (response.errno === 1) {
        this.messageList = response.message_list;
      }
      else {
        ElMessage.error(response.msg);
      }
    },

    async reqGetPositionList() {
      const response = await getPositionList();
      if (response.errno === 1) {
        this.positionList = response.list;
      }
      else {
        ElMessage.error(response.msg);
      }
    },

    async handleContactSelect(index) {
      let contact = null;
      for (let i = 0; i < this.contactList.length; ++i) {
        if (this.contactList[i].user.id.toString() === index) {
          this.contactList[i].unread_count = 0;
          contact = this.contactList[i];
          break;
        }
      }

      this.selectedContact = contact;
      await this.reqGetMessageList(index);
      await this.socketStore.refreshUnreadMessageCount();
    },

    getSelectedPosition() {

      if (this.positionList === undefined) {
        return null;
      }
      for (let i = 0; i < this.positionList.length; ++i) {

        if (this.positionList[i].id.toString() === this.$route.query.positionId) {
          return this.positionList[i];
        }
      }
      return null;
    },

    sendMessageToSocket(messageObject) {
      if (this.selectedContact) {
        let message;
        if (messageObject.msgType === "image" || messageObject.msgType === "file") {
          message = {
            msg_type: messageObject.msgType,
            msg: messageObject.messageContent,
            file: messageObject.file,
            sender_id: this.accountStore.user.id,
            receiver_id: this.selectedContact.user.id,
          }
        }
        else {
          message = {
            msg_type: messageObject.msgType,
            msg: messageObject.messageContent,
            sender_id: this.accountStore.user.id,
            receiver_id: this.selectedContact.user.id,
          }
        }
        this.socketStore.sendMessage(message);
      }
      else {
        ElMessage.error("请选择聊天");
      }
    },

    receiveMessageFromSocket() {
      this.socketStore.ws.addEventListener('message', (event) => {
        const data = JSON.parse(event.data);
        const message = {
          msg_id: data.msg_id,
          msg_type: data.msg_type,
          sender_id: data.sender_id,
          receiver_id: data.receiver_id,
          content: data.content,
          send_time: data.send_time,
          file: data.file,
          set_read: true
        };

        const contactId = message.sender_id === this.accountStore.user.id ? message.receiver_id : message.sender_id;

        // 更新联系人列表contactList最新消息
        for (let i = 0; i < this.contactList.length; ++i) {
          if (this.contactList[i].user.id === contactId) {
            console.log('[debug1]', this.contactList[i].last_message, message);
            this.contactList[i].last_message = message;
            if (message.sender_id !== this.accountStore.user.id) {
              this.contactList[i].unread_count += 1;
            }
            break;
          }
        }

        // 更新聊天窗口消息messageList
        console.log('[debug]', this.messageList);
        if (this.selectedContact && this.selectedContact.user.id === contactId) {
          this.messageList.push(message);
        }
      });
    }
  }
}
</script>

<style scoped>
.container {
  height: calc(100% - 8px - var(--guide-height));
  padding: 0 30px 8px 30px;
}
.aside {
  width: calc(150px + 15%);
  height: 100%;
  padding: 0;
}
.main {
  margin-left: 5px;
  height: 100%;
  padding: 0;
}
</style>